package com.jy.chat.kit.conversation;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;


import io.rong.common.RLog;
import com.jy.chat.kit.IMCenter;
import com.jy.horny.R;
import com.jy.chat.kit.SpArgument;
import com.jy.chat.kit.config.RongConfigCenter;
import com.jy.chat.kit.conversation.extension.InputMode;
import com.jy.chat.kit.conversation.extension.RongExtension;
import com.jy.chat.kit.conversation.extension.RongExtensionViewModel;
import com.jy.chat.kit.conversation.messgelist.processor.IConversationUIRenderer;
import com.jy.chat.kit.conversation.messgelist.status.MessageProcessor;
import com.jy.chat.kit.conversation.messgelist.viewmodel.MessageViewModel;
import com.jy.chat.kit.event.Event;
import com.jy.chat.kit.event.CustomEventTag;
import com.jy.chat.kit.event.uievent.PageDestroyEvent;
import com.jy.chat.kit.event.uievent.PageEvent;
import com.jy.chat.kit.event.uievent.ScrollEvent;
import com.jy.chat.kit.event.uievent.ScrollMentionEvent;
import com.jy.chat.kit.event.uievent.ScrollToEndEvent;
import com.jy.chat.kit.event.uievent.ShowLoadMessageDialogEvent;
import com.jy.chat.kit.event.uievent.ShowWarningDialogEvent;
import com.jy.chat.kit.event.uievent.SmoothScrollEvent;
import com.jy.chat.kit.event.uievent.ToastEvent;
import com.jy.chat.kit.feature.location.LocationUiRender;
import com.jy.chat.kit.feature.reference.ReferenceManager;
import com.jy.chat.kit.http.APIRequest;
import com.jy.chat.kit.manager.MessageProviderPermissionHandler;
import com.jy.chat.kit.manager.hqvoicemessage.HQVoiceMsgDownloadManager;
import com.jy.chat.kit.model.UiMessage;
import com.jy.chat.kit.picture.PictureSelector;
import com.jy.chat.kit.picture.config.PictureConfig;
import com.jy.chat.kit.picture.entity.LocalMedia;
import com.jy.chat.kit.picture.tools.FileUtils;
import com.jy.chat.kit.picture.tools.ToastUtils;
import com.jy.chat.kit.utils.CustomEventUtils;
import com.jy.chat.kit.utils.PermissionCheckUtil;
import com.jy.chat.kit.utils.RongViewUtils;
import com.jy.chat.kit.utils.RouteUtils;
import com.jy.chat.kit.widget.FixedLinearLayoutManager;
import com.jy.chat.kit.widget.adapter.BaseAdapter;
import com.jy.chat.kit.widget.adapter.IViewProviderListener;
import com.jy.chat.kit.widget.adapter.ViewHolder;
import com.jy.chat.kit.widget.refresh.SmartRefreshLayout;
import com.jy.chat.kit.widget.refresh.api.RefreshLayout;
import com.jy.chat.kit.widget.refresh.constant.RefreshState;
import com.jy.chat.kit.widget.refresh.listener.OnLoadMoreListener;
import com.jy.chat.kit.widget.refresh.listener.OnRefreshListener;
import com.jy.chat.kit.widget.refresh.wrapper.RongRefreshHeader;
import com.lib.module_base.utils.SaveDeviceUtil;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.ConversationIdentifier;
import io.rong.imlib.model.Message;

import java.text.MessageFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

/**
 * @author lvz
 */
public class ConversationFragment extends Fragment
        implements OnRefreshListener,
        View.OnClickListener,
        OnLoadMoreListener,
        IViewProviderListener<UiMessage> {
    /**
     * 开启合并转发的选择会话界面
     */
    public static final int REQUEST_CODE_FORWARD = 104;

    private static final int REQUEST_MSG_DOWNLOAD_PERMISSION = 1000;
    private final String TAG = ConversationFragment.class.getSimpleName();
    protected SmartRefreshLayout mRefreshLayout;
    protected RecyclerView mList;
    protected RecyclerView.LayoutManager mLinearLayoutManager;
    protected MessageListAdapter mAdapter;
    protected MessageViewModel mMessageViewModel;
    protected RongExtensionViewModel mRongExtensionViewModel;
    protected RongExtension mRongExtension;
    protected TextView mRcEmptyText;
    protected TextView mNewMessageNum;
    protected TextView mUnreadHistoryMessageNum;
    protected TextView mUnreadMentionMessageNum;
    //头部view
    private View inflate;

    private boolean isFirstLoad = true;
    protected int activitySoftInputMode = 0;
    // 滑动结束是否
    protected boolean onScrollStopRefreshList = false;
    private boolean bindToConversation = false;
    Observer<List<UiMessage>> mListObserver =
            uiMessages -> {
                refreshList(uiMessages);
                if (isFirstLoad) {
                    mList.scrollToPosition(mAdapter.getItemCount() - 1);
                    mList.setVisibility(View.VISIBLE);
                    isFirstLoad = false;
                }
            };
    Observer<Integer> mNewMessageUnreadObserver =
            new Observer<Integer>() {
                @Override
                public void onChanged(Integer count) {
                    if (RongConfigCenter.conversationConfig()
                            .isShowNewMessageBar(mMessageViewModel.getCurConversationType())) {
                        if (count != null && count > 0) {
                            mNewMessageNum.setVisibility(View.VISIBLE);
                            mNewMessageNum.setText(count > 99 ? "99+" : String.valueOf(count));
                        } else {
                            mNewMessageNum.setVisibility(View.INVISIBLE);
                        }
                    }
                }
            };

    Observer<Integer> mHistoryMessageUnreadObserver =
            new Observer<Integer>() {
                @Override
                public void onChanged(Integer count) {
                    if (RongConfigCenter.conversationConfig()
                            .isShowHistoryMessageBar(mMessageViewModel.getCurConversationType())) {
                        if (count != null && count > 0) {
                            mUnreadHistoryMessageNum.setVisibility(View.VISIBLE);
                            mUnreadHistoryMessageNum.setText(
                                    MessageFormat.format(
                                            getString(com.lib.module_res.R.string.rc_unread_message),
                                            count > 99 ? "99+" : count));
                        } else {
                            mUnreadHistoryMessageNum.setVisibility(View.GONE);
                        }
                    }
                }
            };
    Observer<Integer> mNewMentionMessageUnreadObserver =
            new Observer<Integer>() {
                @Override
                public void onChanged(Integer count) {
                    if (RongConfigCenter.conversationConfig()
                            .isShowNewMentionMessageBar(
                                    mMessageViewModel.getCurConversationType())) {
                        if (count != null && count > 0) {
                            mUnreadMentionMessageNum.setVisibility(View.VISIBLE);
                            mUnreadMentionMessageNum.setText(
                                    getString(com.lib.module_res.R.string.rc_mention_messages, "(" + count + ")"));
                        } else {
                            mUnreadMentionMessageNum.setVisibility(View.GONE);
                        }
                    }
                }
            };
    Observer<PageEvent> mPageObserver =
            new Observer<PageEvent>() {
                @Override
                public void onChanged(PageEvent event) {
                    // 优先透传给各模块的 view 处理中心进行处理，如果返回 true, 代表事件被消费，不再处理。
                    for (IConversationUIRenderer processor :
                            RongConfigCenter.conversationConfig().getViewProcessors()) {
                        if (processor.handlePageEvent(event)) {
                            return;
                        }
                    }
                    if (event instanceof Event.RefreshEvent) {
                        if (((Event.RefreshEvent) event).state.equals(RefreshState.RefreshFinish)) {
                            mRefreshLayout.finishRefresh();
                        } else if (((Event.RefreshEvent) event)
                                .state.equals(RefreshState.LoadFinish)) {
                            mRefreshLayout.finishLoadMore();
                        }
                    } else if (event instanceof ToastEvent) {
                        String msg = ((ToastEvent) event).getMessage();
                        if (!TextUtils.isEmpty(msg)) {
                            Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
                        }
                    } else if (event instanceof ScrollToEndEvent) {
                        mList.scrollToPosition(mAdapter.getItemCount() - 1);
                    } else if (event instanceof ScrollMentionEvent) {
                        mMessageViewModel.onScrolled(
                                mList,
                                0,
                                0,
                                mAdapter.getHeadersCount(),
                                mAdapter.getFootersCount());
                    } else if (event instanceof ScrollEvent) {
                        if (mList.getLayoutManager() instanceof LinearLayoutManager) {
                            ((LinearLayoutManager) mList.getLayoutManager())
                                    .scrollToPositionWithOffset(
                                            mAdapter.getHeadersCount()
                                                    + ((ScrollEvent) event).getPosition(),
                                            0);
                        }
                    } else if (event instanceof SmoothScrollEvent) {
                        if (mList.getLayoutManager() instanceof LinearLayoutManager) {
                            ((LinearLayoutManager) mList.getLayoutManager())
                                    .scrollToPositionWithOffset(
                                            mAdapter.getHeadersCount()
                                                    + ((SmoothScrollEvent) event).getPosition(),
                                            0);
                        }
                    }else if (event instanceof PageDestroyEvent) {
                        FragmentManager fm = getChildFragmentManager();
                        if (fm.getBackStackEntryCount() > 0) {
                            fm.popBackStack();
                        } else {
                            if (getActivity() != null) {
                                getActivity().finish();
                            }
                        }
                    } else if (event instanceof ShowWarningDialogEvent) {
                        onWarningDialog(((ShowWarningDialogEvent) event).getMessage());
                    } else if (event instanceof ShowLoadMessageDialogEvent) {
                        showLoadMessageDialog(
                                ((ShowLoadMessageDialogEvent) event).getCallback(),
                                ((ShowLoadMessageDialogEvent) event).getList());
                    }
                }
            };
    private LinearLayout mNotificationContainer;
    private boolean onViewCreated = false;
    private boolean mDisableSystemEmoji;
    private Bundle mBundle;
    private ConversationIdentifier conversationIdentifier;

    private boolean historyMessageListEmpty = false;
    private final RecyclerView.OnScrollListener mScrollListener =
            new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    mMessageViewModel.onScrolled(
                            recyclerView,
                            dx,
                            dy,
                            mAdapter.getHeadersCount(),
                            mAdapter.getFootersCount());
                }

                @Override
                public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE && onScrollStopRefreshList) {
                        onScrollStopRefreshList = false;
                        RLog.d(TAG, "onScrollStateChanged refresh List");
                        refreshList(mMessageViewModel.getUiMessageLiveData().getValue());
                    }
                }
            };

    {
        mAdapter = onResolveAdapter();
    }

    public void initConversation(
            String targetId, Conversation.ConversationType conversationType, Bundle bundle) {
        if (onViewCreated) {
            bindConversation(
                    ConversationIdentifier.obtain(conversationType, targetId, ""), false, bundle);
        } else {
            conversationIdentifier = ConversationIdentifier.obtain(conversationType, targetId, "");
            mBundle = bundle;
        }
    }

    private void bindConversation(
            ConversationIdentifier conversationIdentifier,
            boolean disableSystemEmoji,
            Bundle bundle) {
        if (conversationIdentifier.getType() != null
                && !TextUtils.isEmpty(conversationIdentifier.getTargetId())) {
            for (IConversationUIRenderer processor :
                    RongConfigCenter.conversationConfig().getViewProcessors()) {
                processor.init(
                        this,
                        mRongExtension,
                        conversationIdentifier.getType(),
                        conversationIdentifier.getTargetId());
            }
            mRongExtension.bindToConversation(this, conversationIdentifier, disableSystemEmoji);
            mMessageViewModel.bindConversation(conversationIdentifier, bundle);
            subscribeUi();
            bindToConversation = true;
        } else {
            RLog.e(TAG, "Invalid intent data !!! Must put targetId and conversation type to intent.");
        }
    }

    private void subscribeUi() {
        RongIMClient.getInstance().setMessageExpansionListener(new RongIMClient.MessageExpansionListener() {
            @Override
            public void onMessageExpansionUpdate(Map<String, String> expansion, Message message) {
                IMCenter.getInstance().refreshMessage(message);

            }

            @Override
            public void onMessageExpansionRemove(List<String> keyArray, Message message) {

            }
        });

        mMessageViewModel.getPageEventLiveData().observeForever(mPageObserver);
        mMessageViewModel.getUiMessageLiveData().observeForever(mListObserver);
        mMessageViewModel
                .getNewMessageUnreadLiveData()
                .observe(getViewLifecycleOwner(), mNewMessageUnreadObserver);
        mMessageViewModel
                .getHistoryMessageUnreadLiveData()
                .observe(getViewLifecycleOwner(), mHistoryMessageUnreadObserver);
        mMessageViewModel
                .getNewMentionMessageUnreadLiveData()
                .observe(getViewLifecycleOwner(), mNewMentionMessageUnreadObserver);
        mRongExtensionViewModel
                .getExtensionBoardState()
                .observe(
                        getViewLifecycleOwner(),
                        new Observer<Boolean>() {
                            @Override
                            public void onChanged(final Boolean value) {
                                RLog.d(TAG, "scroll to the bottom:" + mAdapter.getData().size());
                                if (historyMessageListEmpty) {
                                    mRcEmptyText.setVisibility(value ? View.GONE : mAdapter.getData().size() == 0 ? View.VISIBLE : View.GONE);
                                }
                                mList.postDelayed(
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                InputMode inputMode =
                                                        mRongExtensionViewModel
                                                                .getInputModeLiveData()
                                                                .getValue();
                                                if (!Objects.equals(
                                                        inputMode, InputMode.MoreInputMode)
                                                        && Boolean.TRUE.equals(value)) {
                                                    if (mMessageViewModel.isNormalState()) {
                                                        mList.scrollToPosition(
                                                                mAdapter.getItemCount() - 1);
                                                    } else if (!mMessageViewModel
                                                            .isHistoryState()) {
                                                        mMessageViewModel.newMessageBarClick();
                                                    }
                                                }
                                            }
                                        },
                                        150);
                            }
                        });

    }

    @Override
    public void onViewClick(int clickType, UiMessage data) {
        if (MessageProviderPermissionHandler.getInstance()
                .handleMessageClickPermission(data, this)) {
            return;
        }

        mMessageViewModel.onViewClick(clickType, data, getContext());
    }

    @Override
    public boolean onViewLongClick(int clickType, UiMessage data) {
        return mMessageViewModel.onViewLongClick(clickType, data);
    }

    /**
     * 获取顶部通知栏容器
     *
     * @return 通知栏容器
     */
    public LinearLayout getNotificationContainer() {
        return mNotificationContainer;
    }

    /**
     * 隐藏调用showNotificationView所显示的通知view
     *
     * @param notificationView 通知栏 view
     */
    public void hideNotificationView(View notificationView) {
        if (notificationView == null) {
            return;
        }
        View view = mNotificationContainer.findViewById(notificationView.getId());
        if (view != null) {
            mNotificationContainer.removeView(view);
            if (mNotificationContainer.getChildCount() == 0) {
                mNotificationContainer.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 在通知区域显示一个view
     */
    public void showNotificationView(View notificationView) {
        if (notificationView == null) {
            return;
        }
        mNotificationContainer.removeAllViews();
        RongViewUtils.addView(mNotificationContainer, notificationView);
        mNotificationContainer.setVisibility(View.VISIBLE);
    }

    private void refreshList(final List<UiMessage> data) {
        if (!mList.isComputingLayout() && mList.getScrollState() == RecyclerView.SCROLL_STATE_IDLE) {
            mAdapter.setDataCollection(data);
        } else {
            onScrollStopRefreshList = true;
        }
    }

    public boolean onBackPressed() {
        boolean result = false;
        for (IConversationUIRenderer processor :
                RongConfigCenter.conversationConfig().getViewProcessors()) {
            boolean temp = processor.onBackPressed();
            if (temp) {
                result = true;
            }
        }
        if (mMessageViewModel != null) {
            boolean temp = mMessageViewModel.onBackPressed();
            if (temp) {
                result = true;
            }
        }
        if (mRongExtensionViewModel != null) {
            mRongExtensionViewModel.exitMoreInputMode(getContext());
            mRongExtensionViewModel.collapseExtensionBoard();
        }
        return result;
    }

    public void onTitleClick() {
        if (RongConfigCenter.conversationConfig().getConversationClickListener() != null) {
            boolean result =
                    RongConfigCenter.conversationConfig()
                            .getConversationClickListener()
                            .onUserTitleClick(
                                    getActivity(),
                                    conversationIdentifier.getType(),
                                    conversationIdentifier.getTargetId());

        }
    }

    public void onOtherClick() {
        if (!isDestroy(getActivity())) {
            CustomEventUtils.INSTANCE.logEvent(CustomEventTag.Chat_More.name());
            closeExpand();
//            new UserInfoActionPopup(getActivity(), conversationIdentifier.getTargetId(), new UserInfoActionPopup.ActionListener() {
//                @Override
//                public void onReportListener() {
//                    CustomEventUtils.INSTANCE.logEvent(CustomEventTag.Chat_More_Report.name());
//                    new Handler().postDelayed(() -> {
//                        if (!isDestroy(getActivity())) {
////                            new UserInfoReportPopup(getActivity(), conversationIdentifier.getTargetId(), () -> {
////                                CustomEventUtils.INSTANCE.logEvent(CustomEventTag.Chat_More_Reportsuccess.name());
////                            }).showPopupWindow();
//                        }
//                    }, 200);
//
//                }
//
//                @Override
//                public void onBlackListener() {
//                    CustomEventUtils.INSTANCE.logEvent(CustomEventTag.Chat_More_Block.name());
//                    IMCenter.getInstance().removeConversation(
//                            conversationIdentifier.getType(),
//                            conversationIdentifier.getTargetId(),
//                            new RongIMClient.ResultCallback<Boolean>() {
//                                @Override
//                                public void onSuccess(Boolean aBoolean) {
//                                    new Handler().postDelayed(() -> {
//                                        if (!isDestroy(getActivity())) {
//                                            getActivity().finish();
//                                        }
//                                    }, 200);
//                                }
//
//                                @Override
//                                public void onError(RongIMClient.ErrorCode e) {
//                                }
//                            });
//                }
//            }).showPopupWindow();

        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        if (mMessageViewModel != null && bindToConversation) {
            mMessageViewModel.onRefresh();
        }
    }

    public RongExtension getRongExtension() {
        return mRongExtension;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            ReferenceManager.getInstance().hideReferenceView();
        }
        if (requestCode == REQUEST_CODE_FORWARD) {
            if (mMessageViewModel != null) mMessageViewModel.forwardMessage(data);
            return;
        }
        if (mRongExtension != null) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            if (selectList != null && selectList.size() > 0) {
                boolean sendPrivate = data != null && data.getBooleanExtra(PictureConfig.PRIVATE_PHOTO_PREVIEW_TRANSFORM, false);
                if (sendPrivate) {
                    LocalMedia localMedia = selectList.get(0);
                    String path = FileUtils.getPath(getContext(), Uri.parse(localMedia.getPath()));
                    if (path != null) {
//                        UploadPhoto.INSTANCE.uploadFileNew(path, new UploadPhoto.OnLister() {
//                            @Override
//                            public void onSuccess(@NonNull String successPath) {
//                                Log.e(TAG, "onSuccess: " + successPath);
//                                APIRequest.INSTANCE.addPhotoToAlbums(successPath, localMedia.getDuration());
//                            }
//
//                            @Override
//                            public void fail() {
//                            }
//                        });
                    }
                }
            }
            if (mRongExtension != null) {
                mRongExtension.onActivityPluginResult(requestCode, resultCode, data);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (PermissionCheckUtil.checkPermissionResultIncompatible(permissions, grantResults)) {
            if (getContext() != null) {
                ToastUtils.s(getContext(), getString(com.lib.module_res.R.string.rc_permission_request_failed));
            }
            return;
        }

        if (requestCode == REQUEST_MSG_DOWNLOAD_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                HQVoiceMsgDownloadManager.getInstance().resumeDownloadService();
            } else {
                PermissionCheckUtil.showRequestPermissionFailedAlter(
                        this.getContext(), permissions, grantResults);
            }
            return;
        } else if (requestCode == PermissionCheckUtil.REQUEST_CODE_LOCATION_SHARE) {
            if (PermissionCheckUtil.checkPermissions(getActivity(), permissions)) {
                LocationUiRender locationUiRender = null;
                for (IConversationUIRenderer processor :
                        RongConfigCenter.conversationConfig().getViewProcessors()) {
                    if (processor instanceof LocationUiRender) {
                        locationUiRender = (LocationUiRender) processor;
                        break;
                    }
                }

                if (locationUiRender != null) {
                    locationUiRender.joinLocation();
                }
            } else {
                if (getActivity() != null) {
                    PermissionCheckUtil.showRequestPermissionFailedAlter(
                            getActivity(), permissions, grantResults);
                }
            }
        } else if (requestCode
                == MessageProviderPermissionHandler.REQUEST_CODE_ITEM_PROVIDER_PERMISSIONS) {
            MessageProviderPermissionHandler.getInstance()
                    .onRequestPermissionsResult(getActivity(), permissions, grantResults);
        }

        if (requestCode == PermissionCheckUtil.REQUEST_CODE_ASK_PERMISSIONS
                && grantResults.length > 0
                && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
            PermissionCheckUtil.showRequestPermissionFailedAlter(
                    this.getContext(), permissions, grantResults);
        } else {
            mRongExtension.onRequestPermissionResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * findId，绑定监听
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.rc_conversation_fragment, container, false);
        mList = rootView.findViewById(R.id.rc_message_list);
        mRcEmptyText = rootView.findViewById(R.id.rc_empty_text);
        mRongExtension = rootView.findViewById(R.id.rc_extension);
        mRefreshLayout = rootView.findViewById(R.id.rc_refresh);
        mNewMessageNum = rootView.findViewById(R.id.rc_new_message_number);
        mUnreadHistoryMessageNum = rootView.findViewById(R.id.rc_unread_message_count);
        mUnreadMentionMessageNum = rootView.findViewById(R.id.rc_mention_message_count);
        mNotificationContainer = rootView.findViewById(R.id.rc_notification_container);
        mNewMessageNum.setOnClickListener(this);
        mUnreadHistoryMessageNum.setOnClickListener(this);
        mUnreadMentionMessageNum.setOnClickListener(this);
        mLinearLayoutManager = createLayoutManager();
        if (mList != null) {
            mList.setLayoutManager(mLinearLayoutManager);
        }
        mRefreshLayout.setOnTouchListener(
                new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        closeExpand();
                        return false;
                    }
                });
        mAdapter.setItemClickListener(
                new BaseAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, ViewHolder holder, int position) {
                        closeExpand();
                    }

                    @Override
                    public boolean onItemLongClick(View view, ViewHolder holder, int position) {
                        return false;
                    }
                });
        // 关闭动画
        if (mList != null) {
            mList.setAdapter(mAdapter);
            ((SimpleItemAnimator) mList.getItemAnimator()).setSupportsChangeAnimations(false);
            mList.addOnScrollListener(mScrollListener);
            final GestureDetector gd =
                    new GestureDetector(
                            getContext(),
                            new GestureDetector.SimpleOnGestureListener() {
                                @Override
                                public boolean onScroll(
                                        MotionEvent e1,
                                        MotionEvent e2,
                                        float distanceX,
                                        float distanceY) {
                                    closeExpand();
                                    return super.onScroll(e1, e2, distanceX, distanceY);
                                }
                            });
            mList.addOnItemTouchListener(
                    new RecyclerView.OnItemTouchListener() {
                        @Override
                        public boolean onInterceptTouchEvent(
                                @NonNull RecyclerView rv, @NonNull MotionEvent e) {
                            return gd.onTouchEvent(e);
                        }

                        @Override
                        public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                            // Do nothing
                        }

                        @Override
                        public void onRequestDisallowInterceptTouchEvent(
                                boolean disallowIntercept) {
                            // Do nothing
                        }
                    });
        }

        mRefreshLayout.setNestedScrollingEnabled(false);
        mRefreshLayout.setRefreshHeader(new RongRefreshHeader(getContext()));
        mRefreshLayout.setRefreshFooter(new RongRefreshHeader(getContext()));
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setOnLoadMoreListener(this);
        return rootView;
    }

    private RecyclerView.LayoutManager createLayoutManager() {
        LinearLayoutManager linearLayoutManager = new FixedLinearLayoutManager(getContext());
        linearLayoutManager.setStackFromEnd(true);
        return linearLayoutManager;
    }

    /**
     * 判断Activity是否Destroy
     *
     * @param mActivity
     * @return
     */
    public static boolean isDestroy(Activity mActivity) {
        if (mActivity == null || mActivity.isFinishing() || mActivity.isDestroyed()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        if (getActivity() == null || getActivity().getIntent() == null) {
            RLog.e(
                    TAG,
                    "Must put targetId and conversation type to intent when start conversation.");
            return;
        }
        if (!IMCenter.getInstance().isInitialized()) {
            RLog.e(TAG, "Please init SDK first!");
            return;
        }
        super.onViewCreated(view, savedInstanceState);
        initIntentExtra();
        //如果是系统会话，隐藏输入框
        if (SaveDeviceUtil.Companion.getServiceUserCode().equals(conversationIdentifier.getTargetId())) {
            mRongExtension.setVisibility(View.GONE);
        } else {
            mRongExtension.setVisibility(View.VISIBLE);
        }
        mMessageViewModel = new ViewModelProvider(this).get(MessageViewModel.class);
        mRongExtensionViewModel = new ViewModelProvider(this).get(RongExtensionViewModel.class);
        bindConversation(conversationIdentifier, mDisableSystemEmoji, mBundle);
//        APIRequest.INSTANCE.getIMParams(conversationIdentifier.getTargetId(), 1, en -> {
//        });

        onViewCreated = true;
    }

    private void initIntentExtra() {
        Intent intent = getActivity().getIntent();

        if (intent.hasExtra(RouteUtils.CONVERSATION_IDENTIFIER)) {
            ConversationIdentifier identifier =
                    intent.getParcelableExtra(RouteUtils.CONVERSATION_IDENTIFIER);
            if (identifier != null) {
                conversationIdentifier = identifier;
            }
        }
        if (conversationIdentifier == null) {
            String typeValue = intent.getStringExtra(RouteUtils.CONVERSATION_TYPE);
            Conversation.ConversationType type =
                    !TextUtils.isEmpty(typeValue)
                            ? Conversation.ConversationType.valueOf(
                            typeValue.toUpperCase(Locale.US))
                            : Conversation.ConversationType.NONE;
            String targetId = intent.getStringExtra(RouteUtils.TARGET_ID);
            conversationIdentifier = ConversationIdentifier.obtain(type, targetId, "");
        }

        mDisableSystemEmoji = intent.getBooleanExtra(RouteUtils.DISABLE_SYSTEM_EMOJI, false);
        if (mBundle == null) {
            mBundle = intent.getExtras();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getView() == null) {
            return;
        }
        if (mMessageViewModel != null) mMessageViewModel.onResume();
        getView().setOnKeyListener(
                (v, keyCode, event) -> {
                    if (event.getAction() == KeyEvent.ACTION_UP
                            && keyCode == KeyEvent.KEYCODE_BACK) {
                        return onBackPressed();
                    }
                    return false;
                });
        mRongExtension.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mMessageViewModel != null) mMessageViewModel.onPause();
        if (mRongExtension != null) mRongExtension.onPause();
    }

    @Override
    public void onStart() {
        super.onStart();
        // 保存 activity 的原 softInputMode
        FragmentActivity activity = getActivity();
        if (activity != null) {
            activitySoftInputMode = activity.getWindow().getAttributes().softInputMode;
            if (mRongExtension != null && mRongExtension.useKeyboardHeightProvider()) {
                resetSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
            } else {
                resetSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mMessageViewModel != null) mMessageViewModel.onStop();
        resetSoftInputMode(activitySoftInputMode);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        APIRequest.INSTANCE.getIMParams(conversationIdentifier.getTargetId(), 2, entity -> {
//        });
        for (IConversationUIRenderer processor : RongConfigCenter.conversationConfig().getViewProcessors()) {
            processor.onDestroy();
        }
        mList.removeOnScrollListener(mScrollListener);

        if (mMessageViewModel != null) {
            mMessageViewModel.getPageEventLiveData().removeObserver(mPageObserver);
            mMessageViewModel.getUiMessageLiveData().removeObserver(mListObserver);
            mMessageViewModel.getNewMentionMessageUnreadLiveData().removeObserver(mNewMentionMessageUnreadObserver);
            mMessageViewModel.onDestroy();
        }

        if (mRongExtension != null) {
            mRongExtension.onDestroy();
            mRongExtension = null;
        }
        bindToConversation = false;
    }

    private void resetSoftInputMode(int mode) {
        FragmentActivity activity = getActivity();
        if (activity != null) {
            activity.getWindow().setSoftInputMode(mode);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rc_new_message_number) {
            if (mMessageViewModel != null) mMessageViewModel.newMessageBarClick();
        } else if (id == R.id.rc_unread_message_count) {
            if (mMessageViewModel != null) mMessageViewModel.unreadBarClick();
        } else if (id == R.id.rc_mention_message_count) {
            if (mMessageViewModel != null) mMessageViewModel.newMentionMessageBarClick();
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (mMessageViewModel != null && bindToConversation) {
            mMessageViewModel.onLoadMore();
        }
    }

    /**
     * 提示dialog. 例如"加入聊天室失败"的dialog 用户自定义此dialog的步骤: 1.定义一个类继承自 ConversationFragment 2.重写
     * onWarningDialog
     *
     * @param msg dialog 提示
     */
    public void onWarningDialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        if (window == null) {
            return;
        }
        window.setContentView(R.layout.rc_cs_alert_warning);
        TextView tv = window.findViewById(R.id.rc_cs_msg);
        tv.setText(msg);

        window.findViewById(R.id.rc_btn_ok).setOnClickListener(
                v -> {
                    alertDialog.dismiss();
                    if (!isAdded()) {
                        return;
                    }
                    FragmentManager fm = getChildFragmentManager();
                    if (fm.getBackStackEntryCount() > 0) {
                        fm.popBackStack();
                    } else {
                        if (getActivity() != null) {
                            getActivity().finish();
                        }
                    }
                });
    }

    private void showLoadMessageDialog(
            final MessageProcessor.GetMessageCallback callback, final List<Message> list) {
        new AlertDialog.Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                .setMessage(getString(com.lib.module_res.R.string.rc_load_local_message))
                .setPositiveButton(getString(com.lib.module_res.R.string.rc_dialog_ok),
                        (dialog, which) -> {
                            if (callback != null) {
                                callback.onSuccess(list, true);
                            }
                        })
                .setNegativeButton(getString(com.lib.module_res.R.string.rc_cancel),
                        (dialog, which) -> {
                            if (callback != null) {
                                callback.onErrorAsk(list);
                            }
                        })
                .show();
    }

    private void closeExpand() {
        if (mRongExtensionViewModel != null) {
            mRongExtensionViewModel.collapseExtensionBoard();
        }
    }

    /**
     * 获取 adapter. 可复写此方法实现自定义 adapter.
     *
     * @return 会话列表 adapter
     */
    protected MessageListAdapter onResolveAdapter() {
        return new MessageListAdapter(this);
    }

    /**
     * @param view 自定义列表 header view
     */
    public void addHeaderView(View view) {
        mAdapter.addHeaderView(view);
    }

    /**
     * @param view 自定义列表 footer view
     */
    public void addFooterView(View view) {
        mAdapter.addFootView(view);
    }

    /**
     * @param view 自定义列表 空数据 view
     */
    public void setEmptyView(View view) {
        mAdapter.setEmptyView(view);
    }

    /**
     * @param emptyId 自定义列表 空数据的 LayoutId
     */
    public void setEmptyView(@LayoutRes int emptyId) {
        mAdapter.setEmptyView(emptyId);
    }
}
